import generatedRoutes from "virtual:generated-pages";
import { createRouter, createWebHistory } from "vue-router"
import { useUser } from '@/store/useUser'
// import pages from '~pages'
const routes = [
    {
        path:'/',
        name:'login',
        component:()=>import('../pages/index.vue')
    },
    ...generatedRoutes
    , {
        path: '/:pathMatch(.*)*',
        redirect: '/'
    }
]
const router = createRouter({
    history: createWebHistory('/'),
    routes: routes
})

//✅ 全局前置守卫
router.beforeEach((to, from, next) => {  
    const user = useUser()
    // 检查用户token是否存在
    const userToken = user.getToken;
    // 如果是访问登录页，直接放行
    if (to.path === '/') {
        next();
        return;
    }
    if (!userToken) {
        // 如果token不存在，跳转到根目录（登录页）
        console.log('用户token不存在，跳转到登录页');
        next('/');
        return;
    }
    
    // 正常跳转
    next();
})

export default router